package com.ktwlsoft.archivemanage.domain.business.businessService.guiBusiness;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.ktwlsoft.archivemanage.config.exception.ResultException;
import com.ktwlsoft.archivemanage.domain.business.businessService.BasisBusinessManageService;
import com.ktwlsoft.archivemanage.domain.business.businessService.ImgUploadService;
import com.ktwlsoft.archivemanage.domain.business.businessService.NotifyMessageScheduleTask;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.AccountRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.ImgsService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.NotifySetRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.OperationRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.guiBusiness.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.*;
import com.ktwlsoft.archivemanage.domain.dao.entity.guiBusiness.*;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import com.ktwlsoft.archivemanage.payload.guiBusiness.*;
import com.ktwlsoft.archivemanage.payload.mendList.NotifySetRequest;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import com.ktwlsoft.archivemanage.service.utils.DateUtils;
import com.ktwlsoft.archivemanage.service.utils.SnowFlake;
import lombok.Getter;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Date;
import java.util.List;

/**
 * 指导整改
 *
 * @author zhuhe on 2020/4/28 18:01
 * @version 1.0
 */
@Component
public class GuiGuidanceMendListService {

    /**业务指导整改*/
    @Getter
    private final GuiGuidanceMendListRepositoryService mendListRepositoryService;

    /**指导条目整改*/
    @Getter
    private final GuiGuidanceItemMendListRepositoryService itemMendListRepositoryService;

    /**指导整改历史*/
    @Getter
    private final GuidanceMendListHistoryRepositoryService historyRepositoryService;

    /**业务指导*/
    private final GuiBusinessGuidanceRepositoryService repositoryService;

    /**指导条目*/
    private final GuiGuidanceItemRepositoryService itemRepositoryService;

    /**图片*/
    private final ImgsService imgsService;

    /**依据业务管理*/
    private final BasisBusinessManageService basisBusinessManageService;

    /**设置*/
    private final NotifySetRepositoryService notifySetRepositoryService;

    /**业务指导操作日志*/
    private final GuimendListOptLogRepositoryService logRepositoryService;

    /**消息通知*/
    private final NotifyMessageScheduleTask notifyMessageScheduleTask;

    /**账号业务层接口实现类*/
    private final AccountRepositoryService accountRepositoryService;

    public GuiGuidanceMendListService(GuiGuidanceItemMendListRepositoryService itemMendListRepositoryService, GuiGuidanceMendListRepositoryService mendListRepositoryService, GuidanceMendListHistoryRepositoryService historyRepositoryService, GuiBusinessGuidanceRepositoryService repositoryService, GuiGuidanceItemRepositoryService itemRepositoryService, ImgsService imgsService, BasisBusinessManageService basisBusinessManageService, NotifySetRepositoryService notifySetRepositoryService, GuimendListOptLogRepositoryService logRepositoryService, NotifyMessageScheduleTask notifyMessageScheduleTask, AccountRepositoryService accountRepositoryService) {
        this.itemMendListRepositoryService = itemMendListRepositoryService;
        this.mendListRepositoryService = mendListRepositoryService;
        this.historyRepositoryService = historyRepositoryService;
        this.repositoryService = repositoryService;
        this.itemRepositoryService = itemRepositoryService;
        this.imgsService = imgsService;
        this.basisBusinessManageService = basisBusinessManageService;
        this.notifySetRepositoryService = notifySetRepositoryService;
        this.logRepositoryService = logRepositoryService;
        this.notifyMessageScheduleTask = notifyMessageScheduleTask;
        this.accountRepositoryService = accountRepositoryService;
    }

    /**整改图片*/
    private static final String MENDLISTITEM = "MENDLISTITEM";

    /**指导整改图片*/
    private static final String GUIMENDLISTITEM = "GUIMENDLISTITEM";

    /**
      * 列表 on 2020/4/29 16:38
      *
      * @param mendState mendState
      * @param guidanceTimeStart guidanceTimeStart
      * @param guidanceTimeEnd guidanceTimeEnd
      * @param keywords keywords
      * @return Result<?>
      */
    public Result<?> findPage(int pn,int pageSize,Integer mendState,String guidanceTimeStart,String guidanceTimeEnd,String keywords,String type){
        Account account = UserPrincipal.getCurrentUser();
        if("userWeb".equals(type) && account == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("获取不到当前用户");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mendState",mendState);
        jsonObject.put("guidanceTimeStart",guidanceTimeStart != null? DateUtils.dayMinTime(guidanceTimeStart):"");
        jsonObject.put("guidanceTimeEnd",guidanceTimeEnd != null? DateUtils.dayMaxTime(guidanceTimeEnd):"");
        jsonObject.put("keywords",keywords != null?keywords.trim():"");
        if("userWeb".equals(type)){
            jsonObject.put("userId",account != null?account.getId():null);
        }else if("manageWeb".equals(type)){
            if(account != null && !"ADMIN".equals(account.getRoleName()) && !"管理员".equals(account.getRoleName())
                    && !"业务指导处长".equals(account.getRoleName()) && !"正副局长".equals(account.getRoleName())){
                jsonObject.put("manageUserId",account.getId());
            }
        }
        PageInfo<JSONObject> pageInfo = mendListRepositoryService.dataFindPage(pn,pageSize,jsonObject);
        return Result.ok(pageInfo);
    }

    /**
      * 详情 on 2020/4/29 16:54
      *
      * @param id id
      * @return Result<?>
      */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> getDetails(Long id){
        MendListGetDetailsResult result = mendListRepositoryService.getDetails(id);
        if(result == null){
            return Result.body(null, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        result.setMendListId(id);
        GuiGuidanceItem guiGuidanceItem = new GuiGuidanceItem();
        guiGuidanceItem.setGuidanceId(result.getId());
        guiGuidanceItem.setDataState(1);
        result.setItemList(itemMendListRepositoryService.getDetails(guiGuidanceItem));
        if (result.getItemList() != null && result.getItemList().size() > 0) {
            result.getItemList().forEach(value -> {
                Imgs imgs = new Imgs();
                imgs.setBusinessId(value.getId());
                imgs.setBusinessType("GUIDEITEMIMG");
                value.setImgList(imgsService.findList(imgs));
                imgs.setBusinessType(MENDLISTITEM);
                value.setMendListImgList(imgsService.findList(imgs));
                //依据
                List<BasisBusinessManageRequest> requestList = Lists.newArrayList();
                List<BasisBusinessManage> manageList = basisBusinessManageService.getRepositoryService().findList(BasisBusinessManage.builder().businessId(value.getId()).basisType("default").build());
                if(manageList != null){
                    manageList.forEach(basisValue->{
                        BasisBusinessManageRequest request = new BasisBusinessManageRequest();
                        BeanUtils.copyProperties(basisValue,request);
                        try {
                            request.setContent(new String(basisValue.getContent(),"UTF-8"));
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        requestList.add(request);
                    });
                }
                value.setBasisBusinessManages(requestList);
            });
        }
        //附件
        Imgs imgs = new Imgs();
        imgs.setBusinessId(result.getMendListId());
        imgs.setBusinessType("ADDITIONS");
        result.setAdditions(imgsService.findList(imgs));
        //指导整改图片
        imgs.setBusinessId(result.getMendListId());
        imgs.setBusinessType(GUIMENDLISTITEM);
        result.setImgsList(imgsService.findList(imgs));
        //指导员电话
        if(result.getInstructorId() != null) {
            Account account = accountRepositoryService.getById(result.getInstructorId());
            if(account != null){
                result.setInstructorPhone(account.getTeleNum());
            }
        }
        return Result.ok(result);
    }

    /**
      * 下达整改单 on 2020/4/29 18:01
      *
      * @param id id
      * @return Result<?>
      */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> addMendList(Long id){
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            return Result.body(id,ResultType.CHECK_ERROR).withMessage("获取不到当前用户");
        }
        GuiBusinessGuidance guidance = repositoryService.getById(id);
        if(guidance == null){
            return Result.body(id,ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        GuiGuidanceMendList mendList = GuiGuidanceMendList
                .builder()
                .id(SnowFlake.getNextId())
                .guidanceId(id)
                .createName(account.getRealName())
                .createId(account.getId())
                .createTime(new Date())
                .updateName(account.getRealName())
                .updateId(account.getId())
                .updateTime(new Date())
                .mendState(1)
                .build();
        //条目
        List<GuiGuidanceItemMendList> itemMendLists = Lists.newArrayList();
        GuiGuidanceItem guiGuidanceItem = new GuiGuidanceItem();
        guiGuidanceItem.setId(null);
        guiGuidanceItem.setCreatedAt(null);
        guiGuidanceItem.setGuidanceId(id);
        List<GuiGuidanceItem> itemList = itemRepositoryService.findList(guiGuidanceItem);
        if(itemList != null && itemList.size() > 0){
            for(GuiGuidanceItem item:itemList){
                itemMendLists.add(GuiGuidanceItemMendList.builder()
                        .id(SnowFlake.getNextId())
                        .mendListId(mendList.getId())
                        .guidanceItemId(item.getId())
                        .mendRemark("").build());
            }
        }
        try {
            mendListRepositoryService.insert(mendList);
            if(itemMendLists.size() > 0){
                itemMendListRepositoryService.manyInsert(itemMendLists);
            }
            logRepositoryService.save(mendList.getId(),"下达整改单",account);
            notifyMessageScheduleTask.addMendListMessage(mendList);
        }catch (Exception e){
            e.printStackTrace();
            throw new ResultException("操作过程中出现错误",ResultType.BUSINESS_ERROR);
        }
        return Result.ok(id);
    }

    /**
      * 验证 on 2020/4/29 16:46
      *
      * @param id id
      * @param verifyRemark verifyRemark
      * @param ispass ispass
      * @return Result<?>
      */
    public Result<?> verify(Long id,String verifyRemark,Boolean ispass){
        GuiGuidanceMendList mendList = mendListRepositoryService.getById(id);
        if(mendList == null){
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不存在");
        }
        if(!mendList.getMendState().equals(2)){
            return Result.body(id, ResultType.CHECK_ERROR).withMessage("该数据不能验证,因为状态");
        }
        mendList.setVerifyRemark(verifyRemark);
        if(ispass){
            mendList.setMendState(4);
        }else{
            mendList.setMendState(3);
        }
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            account = new Account();
        }
        GuidanceMendListHistory history = GuidanceMendListHistory.builder()
                .id(SnowFlake.getNextId())
                .guidanceId(mendList.getId())
                .mendRemark(mendList.getMendRemark())
                .verifyRemark(verifyRemark)
                .createName(account.getRealName())
                .createId(account.getId())
                .createTime(new Date()).build();
        mendList.setUpdateName(account.getRealName());
        mendList.setUpdateId(account.getId());
        mendList.setUpdateTime(new Date());
        try {
            historyRepositoryService.insert(history);
            mendListRepositoryService.update(mendList);
            if(ispass){
                logRepositoryService.save(mendList.getId(),"验证通过",account);
            }else{
                logRepositoryService.save(mendList.getId(),"验证打回",account);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(id,ResultType.BUSINESS_ERROR).withMessage("操作过程中出现错误");
        }
        notifyMessageScheduleTask.mendListVerify(mendList,ispass);
        GuiBusinessGuidance guidance = repositoryService.getById(mendList.getGuidanceId());
        saveLog(OperationLog.OperationType.VERIFY, (guidance != null?guidance.getUnit():"") + "指导整改" + (guidance != null?"("+ guidance.getGuidanceNum() +")":"") + (ispass?"验证通过":"验证不通过"));
        return Result.ok(id);
    }

    /**
      * 指导整改设置 on 2020/4/30 10:04
      *
      * @param request request
      * @return Result<?>
      */
    public Result<?> setNotifySet(NotifySetRequest request) {
        NotifySet notifySet = notifySetRepositoryService.findByName("GUIDANCE_MEND_WARNING");
        if (notifySet == null) {
            return Result.body(null,ResultType.CHECK_ERROR).withMessage("未找到“指导整改”通知设定，请确认数据库中有默认数据");
        }
        notifySet.setNotifyPeriod(request.getPeriod());
        notifySet.setNotifyPeriodUnit(request.getUnit());
        notifySetRepositoryService.updateSet(notifySet);
        saveLog(OperationLog.OperationType.SET, "更改了指导整改设置");
        return Result.ok(request);
    }

    /**
      * 操作日志 on 2020/4/30 10:58
      *
      * @param guiMendId guiMendId
      * @return Result<?>
      */
    public Result<?> operationLog(int pn,int pageSize,Long guiMendId){
        if(guiMendId == null || guiMendId <= 0){
            return Result.body(guiMendId,ResultType.CHECK_ERROR).withMessage("指导整改id不能为空");
        }
        return Result.ok(logRepositoryService.findPage(pn,pageSize,GuimendListOptLog.builder().guiMendId(guiMendId).build()));
    }

    /**
      * 整改提交 on 2020/4/30 11:23
      *
      * @param request request
      * @return Result<?>
      */
    @Transactional(rollbackFor = Exception.class)
    public Result<?> mendListCommit(MendListCommitRequest request){
        GuiGuidanceMendList mendList = mendListRepositoryService.getById(request.getId());
        if(mendList == null){
            return Result.body(request.getId(),ResultType.CHECK_ERROR).withMessage("该整改单不存在");
        }
        Account account = UserPrincipal.getCurrentUser();
        if(account == null){
            return Result.body(null,ResultType.CHECK_ERROR).withMessage("获取不到当前用户");
        }
        mendList.setMendRemark(request.getMendRemark());
        mendList.setUpdateName(account.getRealName());
        mendList.setUpdateId(account.getId());
        mendList.setUpdateTime(new Date());
        mendList.setMendState(2);
        List<GuiGuidanceItemMendList> itemList = Lists.newArrayList();
        if(request.getItemList() != null && request.getItemList().size() > 0){
            for(GuidanceItemMendListRequest item:request.getItemList()){
                GuiGuidanceItemMendList itemMendList = GuiGuidanceItemMendList.builder()
                        .id(SnowFlake.getNextId())
                        .guidanceItemId(item.getGuidanceItemId())
                        .mendListId(mendList.getId())
                        .mendRemark(item.getMendRemark()).build();
                itemList.add(itemMendList);
                //整改图片
                if(item.getImgsList() != null && item.getImgsList().size() > 0){
                    ImgUploadService.handleImg(item.getGuidanceItemId(),MENDLISTITEM,item.getImgsList());
                }
            }
        }
        //新增指导整改图片
        if(request.getImgsList() != null && request.getImgsList().size() > 0){
            ImgUploadService.handleImg(mendList.getId(),GUIMENDLISTITEM,request.getImgsList());
        }
        try {
            //更新指导整改
            mendListRepositoryService.update(mendList);
            //删除条目整改
            itemMendListRepositoryService.deleteByMendListId(mendList.getId());
            //新增条目整改
            if(itemList.size() > 0){
                itemMendListRepositoryService.manyInsert(itemList);
            }
            //新增操作日志
            logRepositoryService.save(mendList.getId(),"整改提交",account);
            //消息通知
            notifyMessageScheduleTask.addMendList(mendList);
        }catch (Exception e){
            e.printStackTrace();
            return Result.body(request.getId(),ResultType.BUSINESS_ERROR).withMessage("操作过程中出现错误");
        }
        return Result.ok(request.getId());
    }

    /**
      * 删除整改单及相关数据-硬删 on 2020/4/29 10:55
      *
      * @param id 整改单id
      * @return int
      */
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id){
        GuiGuidanceMendList mendList = mendListRepositoryService.getById(id);
        if(mendList == null){
            return 0;
        }
        List<Long> itemIdList = null;
        List<Long> historyIdList = null;
        List<GuiGuidanceItemMendList> list = itemMendListRepositoryService.getByMendListId(mendList.getId());
        if(list != null){
            itemIdList = Lists.newArrayList();
            for(GuiGuidanceItemMendList value:list){
                itemIdList.add(value.getId());
                ImgUploadService.deleteByBIdAndBType(value.getId(),MENDLISTITEM);
            }
        }
        List<GuidanceMendListHistory> list1 = historyRepositoryService.findList(GuidanceMendListHistory.builder().guidanceId(mendList.getId()).build());
        if(list1 != null){
            historyIdList = Lists.newArrayList();
            for(GuidanceMendListHistory value:list1){
                historyIdList.add(value.getId());
            }
        }
        try {
            mendListRepositoryService.deleteById(mendList.getId());
            if(itemIdList != null && itemIdList.size() > 0){
                itemMendListRepositoryService.deleteByIds(itemIdList);
            }
            if(historyIdList != null && historyIdList.size() > 0){
                historyRepositoryService.deleteByIds(historyIdList);
            }
        }catch (Exception e){
            e.printStackTrace();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }
        return 1;
    }

    /**
     * 新增日志 on 2019/11/14 10:37
     *
     * @param operationType 操作类型
     * @param description   描述
     */
    private void saveLog(OperationLog.OperationType operationType, String description) {
        OperationRepositoryService.saveLog(new SaveLogRequest(
                operationType,
                description,
                "指导整改",
                OperationLog.BusinessType.BUSINESS
        ));
    }
}